import Taro, { Component } from '@tarojs/taro'
import { View, Text, Swiper, SwiperItem, Map, Image } from '@tarojs/components'
import './index.scss'
import { AtButton, AtFab, AtCard, AtInputNumber, AtImagePicker } from 'taro-ui'
import AtTabBar_index from '../../components/AtTabBar_index';
// 引入SDK核心类
import requets from '../../service/api';
var QQMapWX = require('../../assets/qqmap-wx-jssdk1.2/qqmap-wx-jssdk');
var yiyuan_icon = require('../../assets/img/yiyuan_icon.png')
var liang = require('../../assets/img/liang.png')
var shouji = require('../../assets/img/shouji.png')
var cheqian = require('../../assets/img/cheqian.png')
var chehou = require('../../assets/img/chehou.png')
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'D43BZ-P7MKO-N4TWG-SGR4H-SLJIE-YAFTN' // 必填
});
Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份 
    "d+": this.getDate(),                    //日 
    "h+": this.getHours(),                   //小时 
    "m+": this.getMinutes(),                 //分 
    "s+": this.getSeconds(),                 //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds()             //毫秒 
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}
export default class Index extends Component {
  config = {
    navigationBarTitleText: '信息填报'
  }
  state = {
    tong: 0,
    qianke: 0,
    loading: false,
    hou_cx_files: [],
    hou_kf_files: [],
    qian_kf_files: [],
    qian_cx_files: [],
    hou_cx_files2: [],
    hou_kf_files2: [],
    qian_kf_files2: [],
    qian_cx_files2: [],
    hospitalAddress: '',
    hospitalName: '',
    pages: '',
    hospitalId: '',
    userId: '',
    files: [
    ],
    auditType: '',
    time: '',
    disabled: false,
    qian_cx_filess_img: '',
    qian_kf_filess_img: '',
    hou_cx_filess_img: '',
    hou_kf_filess_img: '',
    createTime: '',
    next: ''
  }

  componentWillMount() { }

  componentDidMount() {

    Taro.getStorage({
      key: 'userId',
      success: (res) => {
        // console.log(res.data)
        this.setState({
          userId: res.data
        })
      }
    })
    // console.log(this.$router.params, 123456)

    if (this.$router.params) {
      if (this.$router.params.pages === '收集上报') {
        const { hospitalAddress, hospitalName, pages, hospitalId, next } = this.$router.params
        this.setState({
          hospitalAddress, hospitalName, pages, hospitalId, next
        })
      }



      if (this.$router.params.pages === '历史查询') {


        requets.baseOptions({
          url: `/zjn-web/zjn/collector/record/getCollectorRecord?recordId=${this.$router.params.recordId}`,
          method: 'GET',
          data: {}
        }).then((res) => {
          if (res.data.rc === 0) {
            const { auditContent, createTime, collectorWeight, hospitalAddress, hospitalName, hospitalId, auditType, collectorBucketNum, frontCarriageImg, laterCarriageImg, laterWarehouseImg, frontWarehouseImg } = res.data.ret
            let createTimes = new Date(createTime).format("yyyy-MM-dd hh:mm:ss")
            this.setState({
              hospitalAddress, hospitalName, hospitalId,
              tong: collectorBucketNum,
              qianke: collectorWeight,
              qian_cx_filess_img: frontCarriageImg ? 'https://zjn.cloudhw.cn/zjn-web/zjn/common/filehandle/showImage?filepath=' + frontCarriageImg : '',
              qian_kf_filess_img: frontWarehouseImg ? 'https://zjn.cloudhw.cn/zjn-web/zjn/common/filehandle/showImage?filepath=' + frontWarehouseImg : '',
              hou_cx_filess_img: laterCarriageImg ? 'https://zjn.cloudhw.cn/zjn-web/zjn/common/filehandle/showImage?filepath=' + laterCarriageImg : '',
              hou_kf_filess_img: laterWarehouseImg ? 'https://zjn.cloudhw.cn/zjn-web/zjn/common/filehandle/showImage?filepath=' + laterWarehouseImg : '',
              createTime: createTimes,
              auditType: auditType,
              auditContent
            })
          }
        })
        this.setState({
          disabled: true,
          pages: '历史查询',
        })
      }


    }
  }

  componentWillUnmount() { }

  componentDidShow() { }

  componentDidHide() { }



  onChangeAtImagePicker = (v, files, operationType) => {
    console.log(v, files, operationType)
    let v2 = v + '2'
    // this.uploadFile(files[0].url)
    // this.setState({
    //   files
    // })

    if (operationType == 'add') {
      wx.uploadFile({
        url: 'https://zjn.cloudhw.cn/zjn-web/zjn/common/filehandle/uploadFile', //仅为示例，非真实的接口地址
        filePath: files[0].url,
        name: 'file',
        formData: {
          'user': 'test'
        },
        header: { 'content-type': 'application/json' },
        success: (res) => {
          // console.log(res)
          const data = JSON.parse(res.data)
          const url = 'https://zjn.cloudhw.cn/zjn-web/zjn/common/filehandle/showImage?filepath=' + data.ret
          //do something
          this.setState({
            [v]: [{
              url: url
            }],
            [v2]: [{
              url: data.ret
            }]
          })
        },
        fail: (res) => {
          // console.log(res)
        }
      })
    }

    if (operationType == 'remove') {
      this.setState({
        [v]: [],
        [v2]: []
      })
    }



  }
  uploadFile = (file) => {

    requets.baseOptions({
      url: `/zjn-web/zjn/common/filehandle/uploadFile`,
      method: 'POST',
      data: { file: file }
    }).then((res) => {
      // console.log(res)
    })
  }
  onImageClick(index, file) {
    // console.log(index, file)
  }

  handleChange_AtInputNumber = (v, val) => {
    this.setState({
      [v]: val
    })
  }


  onSubmit = () => {
    this.setState({
      loading: true
    })
    let params = {
      collectorBucketNum: this.state.tong,
      collectorWeight: this.state.qianke,
      hospitalId: this.state.hospitalId,
      frontCarriageImg: this.state.qian_cx_files2.length > 0 ? this.state.qian_cx_files2[0].url : '',
      frontWarehouseImg: this.state.qian_kf_files2.length > 0 ? this.state.qian_kf_files2[0].url : '',
      laterCarriageImg: this.state.hou_cx_files2.length > 0 ? this.state.hou_cx_files2[0].url : '',
      laterWarehouseImg: this.state.hou_kf_files2.length > 0 ? this.state.hou_kf_files2[0].url : '',
      submitSite: '',
      userId: this.state.userId
    }
    requets.baseOptions({
      url: `/zjn-web/zjn/collector/record/insertCollectorRecord`,
      method: 'POST',
      data: params
    }).then((res) => {
      if (res.data.rc === 0) {
        // this.setState({
        //   loading: false
        // })
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1000
        })
        setTimeout(() => {
          if (this.state.next == 'renwu') {
            Taro.redirectTo({
              url: '/pages/renwu/index'
            })
          }else{
            Taro.redirectTo({
              url: '/pages/index/index'
            })
          }

        }, 1000)

      } else {
        wx.showToast({
          icon: 'none',
          title: res.data.err,
          duration: 1000
        })
        this.setState({
          loading: false
        })
      }

    })
  }

  getImg = (img) => {
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  }



  render() {
    const { pages, disabled, hou_cx_files, hou_kf_files, tong, hospitalName, hospitalAddress, qianke, qian_kf_files, qian_cx_files, loading, auditType, auditContent } = this.state

    return (
      <View className='index'>
        <AtCard
          isFull={true}
          note={hospitalAddress}
          // extra='额外信息'
          title='收集对象'
          thumb={shouji}
        >
          {hospitalName}
          {
            pages == '历史查询' ? <View>
              {createTime}
              {
                auditType == 3 ? <View>拒绝理由 : {auditContent}</View> : ''
              }

            </View> : ''
          }
        </AtCard>

        <AtCard
          isFull={true}
          title='医废收集量'
          thumb={liang}
        >
          <View className="AtInputNumber">


            <View>
              桶数:<AtInputNumber
                disabled={disabled}
                min={0}
                max={999}
                step={1}
                value={tong}
                onChange={this.handleChange_AtInputNumber.bind(this, 'tong')}
                className="tongshu"
              />
              <AtInputNumber
                disabled={disabled}
                min={0}
                max={999}
                step={0.1}
                value={qianke}
                onChange={this.handleChange_AtInputNumber.bind(this, 'qianke')}
              /> 千克
            </View>
          </View>
        </AtCard>

        <AtCard
          isFull={true}
          title='装车前照片'
          thumb={cheqian}
        >
          <View className="AtInputNumber">


            <View className="AtInputNumber">
              库房:
              {
                pages == '历史查询' ? <Image src={this.state.qian_kf_filess_img} className="AtImagePicker" onClick={this.getImg.bind(this,this.state.qian_kf_filess_img)}/> :
                  <AtImagePicker
                    className="AtImagePicker"
                    length={1}
                    // sizeType={[10, 10]}
                    files={this.state.qian_kf_files}
                    onChange={this.onChangeAtImagePicker.bind(this, 'qian_kf_files')}

                  />
              }

            </View>

            <View className="AtInputNumber">
              车厢:
              {
                pages == '历史查询' ? <Image src={this.state.qian_cx_filess_img} className="AtImagePicker" onClick={this.getImg.bind(this,this.state.qian_cx_filess_img)}/> :
                  <AtImagePicker
                    className="AtImagePicker"
                    length={1}
                    // sizeType={[10, 10]}
                    files={this.state.qian_cx_files}
                    onChange={this.onChangeAtImagePicker.bind(this, 'qian_cx_files')}

                  />
              }

            </View>
          </View>
        </AtCard>

        <AtCard
          isFull={true}
          title='装车后照片'
          thumb={chehou}
        >
          <View className="AtInputNumber">


            <View className="AtInputNumber">
              库房:
              {
                pages == '历史查询' ? <Image src={this.state.hou_kf_filess_img} className="AtImagePicker"  onClick={this.getImg.bind(this,this.state.hou_kf_filess_img)}/> :
                  <AtImagePicker
                    className="AtImagePicker"
                    length={1}
                    // sizeType={[10, 10]}
                    files={this.state.hou_kf_files}
                    onChange={this.onChangeAtImagePicker.bind(this, 'hou_kf_files')}

                  />
              }

            </View>

            <View className="AtInputNumber">
              车厢:
              {
                pages == '历史查询' ? <Image src={this.state.hou_cx_filess_img} className="AtImagePicker"  onClick={this.getImg.bind(this,this.state.hou_cx_filess_img)}/> :
                  <AtImagePicker
                    className="AtImagePicker"
                    length={1}
                    // sizeType={[10, 10]}
                    files={this.state.hou_cx_files}
                    onChange={this.onChangeAtImagePicker.bind(this, 'hou_cx_files')}

                  />
              }
            </View>
          </View>
        </AtCard>
        {
          pages == '历史查询' ? '' : <AtButton loading={loading} type='primary' className='tijiao' onClick={this.onSubmit}>提交</AtButton>
        }

        <View style={{ height: '20px' }}></View>
      </View>
    )
  }
}
